<?php
    /**
     * Created by PhpStorm.
     * 版权所有: 2019~2022 [ hhygyl ]
     * Date: 2019/6/26-15:38
     * Link: http://luckyadmin.luckyhhy.cn
     * FileName: SystemBase.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     *
     **************************************************************
     *                                                            *
     *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
     *    |                     ______                     |      *
     *    |                  .-"      "-.                  |      *
     *    |                 /            \                 |      *
     *    |     _          |              |          _     |      *
     *    |    ( \         |,  .-.  .-.  ,|         / )    |      *
     *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *
     *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
     *    |           "=._"(_     ^^     _)"_.="           |      *
     *    |               "=\__|IIIIII|__/="               |      *
     *    |              _.="| \IIIIII/ |"=._              |      *
     *    |    _     _.="_.="\          /"=._"=._     _    |      *
     *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
     *    |    > _.="                            "=._ <    |      *
     *    |   (_/                                    \_)   |      *
     *    |                                                |      *
     *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
     *                                                            *
     *                    JUST FIND YOUR BUG !                    *
     **************************************************************
     */

    namespace app\admin\controller;


    use app\common\controller\AdminBase;
    use service\JsonService;
    use service\UtilService;
    use think\Db;
    use think\Exception;
    use think\Session;

    class SystemBase extends AdminBase
    {

        protected static $admin_info;
        protected static $admin_ID;
        protected $email_tem;
        protected $wx_config; //微信支付配置
        protected $ali_config;

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub

            //登录检测
            if(!Session::has('admin_info.username')) {
                $this->redirect('Login/index');
            }

            self::$admin_info = Session::get("admin_info");//
            $this->assign("admin_info", self::$admin_info);

            self::$admin_ID= (int)self::$admin_info['id']; //ID

            $role_ids = (int)self::$admin_info['role_id']; //角色ID
            //验证用户是否更改权限组
            $role_id =Db::name('admin_member') -> where('id', '=', self::$admin_info['id']) -> value('role_id');
            if($role_id == $role_ids){
                // 正确
            }else{
                // 注销，重新登陆
                session('admin_info', null); //注销
                header('Location:' . url('Login/index'));
                exit();
            }

            $this->email_tem=new \app\admin\model\Email(); //实例化邮件模板模型

            $this->wxpay_config();
        }


        /**
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: wxpay_config
         * @describe:微信支付配置
         */
        protected function wxpay_config(){
            $this->wx_config = [
                'token'          => 'test',
                'appid'          => 'wxd678efh567hg6787',
                'appsecret'      => '71308e96a204296c57d7cd4b21b883e8',
                'encodingaeskey' => 'BJIUzE0gqlWy0GxfPp4J1oPTBmOrNDIGPNav1YFH5Z5', //开启了安全加密的必须配置
                // 配置商户支付参数（可选，在使用支付功能时需要）
                'mch_id'         => "1230000109",
                'mch_key'        => 'IKI4kpHjU94ji3oqre5zYaQMwLHuZPmj',
                // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
                'ssl_key'        => '',
                'ssl_cer'        => '',
                // 缓存目录配置（可选，需拥有读写权限）
                'cache_path'     => '',
            ];
        }



        /**
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: aliypay_config
         * @describe:支付宝支付配置
         */
        protected function aliypay_config(){
            $this->ali_config = [
                // 沙箱模式
                'debug'       => true,
                // 应用ID
                'appid'       => '2016090900468879',
                // 支付宝公钥(1行填写)
                'public_key'  => 'MB',
                // 支付宝私钥(1行填写)
                'private_key' => 'MIIEvQ5rbObEMz3XqtIF+8kcAC=',
                // 支付成功通知地址
                'notify_url'  => '', // 可以应用的时候配置哦
                // 网页支付回跳地址
                'return_url'  => '', // 可以应用的时候配置哦
            ];
        }



        /**
         * 成功提示一直持续
         * @param $msg
         * @param int $backUrl
         * @param string $title
         * @return mixed
         */
        protected function successfulNoticeLast($msg = '操作成功', $backUrl = 0, $info = '')
        {
            return $this->successfulNotice($msg, $backUrl, $info, 0);
        }

        /**
         * @param string $msg
         * @param int $url
         * @param $wait
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: failed
         * @describe:错误提醒页面
         */
        protected function failed($msg = '哎呀…亲…您访问的页面出现错误', $url = 0, $wait)
        {
            $this->assign(compact('msg', 'url', 'wait'));
            return $this->fetch('public/jump');
        }


        /**
         * @param string $msg
         * @return mixed
         * @author: hhygyl
         * @name: exception
         * @describe:异常抛出
         */
        protected function exception($msg = '无法打开页面')
        {
            $this->assign(compact('msg'));
            return $this->fetch('public/500');
        }


        /**
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: false_to
         * @describe:系统演示
         */
        protected function false_to(){
            $this->error("系统演示，无操作权限");
        }



        /**
         * @param $describe
         * @return bool|int
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: AddLogs
         * @describe:添加操作日志
         */
        protected function AddLogs($describe){
            if(empty($describe)){
                $describe="暂无描述";
            }
            $ars = ['describe' => $describe, 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
            return addLogs($ars); //
        }


        /**
         * @param $table
         * @param $id
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: DeleteData
         * @describe: 删除
         */
        public function DeleteData($table,$id){
            if(empty($table)){
                $this->error("请指定表");
            }
            try{
                $res=db($table)->where(['id' => ['in', $id]])->delete();
                if($res){
                    $this->success("删除成功");
                }else{
                    $this->error("删除失败");
                }
            }catch (Exception $exception){
                $this->error($exception->getMessage());
            }

        }


        public function no_rule(){
            $this->error("系统演示无权限");
        }



        /**
         * @param $title
         * @param $message
         * @param $address
         * @return bool
         * @throws \phpmailerException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: Send_Maile
         * @describe:邮件发送
         */
        public function Send_Maile($title,$message,$address){
            vendor('phpmailer.PHPMailerAutoload');
            $mail = new \PHPMailer();
            // 设置PHPMailer使用SMTP服务器发送Email
            $mail->IsSMTP();
            // 设置邮件的字符编码，若不指定，则为'UTF-8'
            $mail->CharSet='UTF-8';
            // 添加收件人地址，可以多次使用来添加多个收件人
            $mail->AddAddress($address);
            $data=db("setting")->where("key","email")->find();
            $data=json_decode($data["value"]);

            $from = $data->from_email;
            $fromname = $data->from_name;
            $smtp = $data->smtp;
            $username = $data->username;
            $password = $data->password;
            // 设置邮件正文
            $mail->Body=$message;
            // 设置邮件头的From字段。
            $mail->From=$from;
            // 设置发件人名字
            $mail->FromName=$fromname;
            // 设置邮件标题
            $mail->Subject=$title;
            // 设置SMTP服务器。
            $mail->Host=$smtp;
            // 设置使用ssl加密方式登录鉴权
            $mail->SMTPSecure = 'ssl';
            // 设置ssl连接smtp服务器的远程服务器端口号
            $mail->Port = 465;
            // 设置为"需要验证" ThinkPHP 的config方法读取配置文件
            $mail->SMTPAuth=true;
            //设置html发送格式
            $mail->isHTML(true);
            // 设置用户名和密码。
            $mail->Username=$username;
            $mail->Password=$password;
            // 发送邮件。
            return($mail->Send());

        }



    }